import axios from "axios"
import config from '../config'
import { ElMessage } from "element-Plus"

const NETWORK_ERROR = '网络请求失败,请稍后重试......'

const service = axios.create({
    baseURL: config.baseApi
})

//请求前操作
service.interceptors.request.use((req) => {
    //可以定义header，设置JWT-token
    return req
})

//请求后操作
service.interceptors.response.use((resp) => {
    //console.log(resp.data);
    const { code, data, msg } = resp.data
    if (code == 200) {
        return data
    } else {
        ElMessage.error(msg || NETWORK_ERROR);
        return Promise.reject(msg || NETWORK_ERROR)
    }
})

function request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() == 'get') {
        options.params = options.data
    }
    let isMock = config.mock
    if (typeof options.mock !== "undefined") {
        isMock = options.mock
    }
    //生产环境不使用mockApi
    if (config.env == 'prod') {
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
    }
    return service(options)
}
export default request